package com.ssc.jasperttest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class AdherentList implements Iterable<Adherent> {
	private List<Adherent> list = new ArrayList<Adherent>();

	public AdherentList(List<Adherent> l) {
		list = l;
	}

	public AdherentList() {

	}

	@Override
	public Iterator<Adherent> iterator() {

		return list.iterator();
	}

	public void add(Adherent adh) {
		Adherent adhSameFamilly = findSameFamilyAndSameAddress(adh);
		if (adhSameFamilly == null) {
			list.add(adh);
			adh.setLibEmail1("Mail");
			adh.setLibPort1("Port");
			adh.setLibEmail2("Mail");
			adh.setLibPort2("Port");
		} else {
			if (adhSameFamilly.isMarriedWith(adh)) {
				adhSameFamilly.setSpouse(adh);
				adh.setSpouse(adhSameFamilly);
				if(adhSameFamilly.isMale()){
					adhSameFamilly.setLibEmail1(adhSameFamilly.getPrenomAbrege());
					adhSameFamilly.setLibPort1(adhSameFamilly.getPrenomAbrege());
					adhSameFamilly.setLibEmail2(adh.getPrenomAbrege());
					adhSameFamilly.setLibPort2(adh.getPrenomAbrege());
					adhSameFamilly.setPort2(adh.getPort1());
					adhSameFamilly.setEmail2(adh.getEmail1());
				}
				else {
					adhSameFamilly.setLibEmail2(adhSameFamilly.getPrenom());
					adhSameFamilly.setLibPort2(adhSameFamilly.getPrenom());
					adhSameFamilly.setLibEmail1(adh.getPrenom());
					adhSameFamilly.setLibPort1(adh.getPrenom());
				}

			} else {
				adhSameFamilly.addChild(adh);
			}
		}
	}

	public Adherent findSameFamily(Adherent adh) {
		Adherent result = null;
		for (Adherent a : list) {
			if (a.isSameFamillyWith(adh)) {
				result = a;
				break;
			}
		}
		return result;

	}
	public Adherent findSameFamilyAndSameAddress(Adherent adh) {
		Adherent result = null;
		for (Adherent a : list) {
			if (a.isSameFamillyWith(adh) && a.isSameAddressWith(adh)) {
				result = a;
				break;
			}
		}
		return result;
		
	}

	public List<Adherent> getReadOnlyInternList() {
		return Collections.unmodifiableList(list);
	}
}
